const express = require('express');
const router = express.Router();
const utils = require('../../utils');

const filters = [
    {
        Name: '标题',
        Type: 'String',
    },
    {
        Name: '描述',
        Type: 'String',
    },
];

// services
router.get('/',
    (req, res, next) => {
        // query
        res.locals.filter = Object.assign(
            {}, 
            res.app.modules['input-field'].generateQueryFilter(filters, req.query), 
            res.locals.filter, 
            utils.makeQueryFilters(req, 'service'),
            { Status: '1', Deleted: false, Freeze: { $exists: false, $ne: true } }
        );

        res.locals.fields = [
            'id',
            'LastUpdateDate',
            '标题',
            '时间',
            '标题',
            '图片',
            '描述',
        ];
        res.locals.options = {
            sort: { 推荐指数: 'desc', 时间: 'desc', LastUpdateDate: 'desc' },
            lean: true
        };

        return next();
    },
    router.FindDocuments('services', false, (req, res) => {
        if(!res.locals.data || !res.locals.data.total) return;

        (res.locals.data.docs || []).forEach(pol => {
            pol.描述 = utils.repalceHtmlToText(pol.描述 || '');
            pol.时间 = pol.时间 || pol.LastUpdateDate;
            delete pol.LastUpdateDate;
        });
    })
);

// service details
router.get('/:id',
    (req, res, next) => {
        res.locals.filter = { id: req.params.id, Status: '1', Deleted: false, Freeze: { $exists: false, $ne: true } };
        res.locals.fields = [
            'id',
            'LastUpdateDate',
            '推荐指数',
            '日期',
            
            '标题',
            '描述',
            '申请字段',
        ];
        res.locals.options = {
            lean: true
        };

        return next();
    },
    router.FindDocuments('services', false, async (req, res) => {
        if(res.locals.data && res.locals.data.total) {
            res.locals.data = res.locals.data.docs[0];

            // application
            const application = req.user && await res.app.models.sapplication.findOne({
                服务: res.locals.data.id,
                User: req.user.id,
            });

            if (application) {
                res.locals.data.applyStatus = application.Status;
            }
        } else {
            res.locals.data = {};
        }
    }),
);

// related
router.get('/related/:id',
    (req, res, next) => {
        // query
        res.locals.filter = Object.assign(
            {}, 
            res.app.modules['input-field'].generateQueryFilter(filters, req.query), 
            res.locals.filter, 
            utils.makeQueryFilters(req, 'service'),
            { Status: '1', Deleted: false, Freeze: { $exists: false, $ne: true } },
            { id: { $ne: req.params.id }},
        );

        res.locals.fields = [
            'id',
            'LastUpdateDate',
            '标题',
            '时间',
            '图片',
            '描述',
        ];
        res.locals.options = {
            sort: { 推荐指数: 'desc', 时间: 'desc', LastUpdateDate: 'desc' },
            lean: true
        };

        return next();
    },
    router.FindDocuments('services', false, async (req, res) => {
        if(!res.locals.data || !res.locals.data.total) return;

        for (let i = 0; i < res.locals.data.docs.length; i += 1) {
            const doc = res.locals.data.docs[i];

            doc.描述 = utils.repalceHtmlToText(doc.描述 || '');
            doc.日期 = doc.时间 || doc.LastUpdateDate;
            delete doc.LastUpdateDate;
            delete doc.时间;
        }
    })
);

router.post('/apply/:id', 
    async (req, res, next) => {
        // 必须登录才能申请服务
        if (!req.user || !req.user.id) {
            res.makeError(401, '登录后方可申请。');
            return next('route');
        }

        const sid = req.params.id;
        if (!sid) {
            res.makeError(400, '请选择服务。');
            return next('route');
        }

        const theService = await res.app.models.services.findOne({id: sid});
        if (!theService || !theService.申请字段) {
            res.makeError(400, '选择的服务不存在或没有定义申请字段信息。');
            return next('route');
        }

        const existsApplications = await res.app.models.sapplication.countDocuments({
            User: req.user.id,
            服务: sid,
        });
        if (existsApplications > 0) {
            res.makeError(400, '您已申请过此服务！');
            return next('route');
        }

        const appFlow = await res.app.models['flow'].findOne({ Code: 'sapplication' });

        if (!appFlow) {
            await res.makeError(400, '此功能尚未启用！');
            return next();
        }

        const fields = theService.申请字段.map((af) => af.Name);
        const bodyKeys = Object.keys(req.body);

        const flowInfo = {
            Flow: appFlow.id,
            Steps: [null, {
                StartDate: new Date(),
                Status: '1'
            }, {
                StartDate: new Date(),
                Status: '0'
            }],
            Status: "0",
            CurrentStep: 2,
        };

        const doc = {
            服务: sid,
        };

        for (let i = 0; i < bodyKeys.length; i += 1) {
            const bk = bodyKeys[i];

            if (fields.indexOf(bk) >= 0) {
                doc[bk] = req.body[bk];
            }
        }

        res.locals.body = {
            User: req.user.id,
            ...flowInfo,
            ...doc,
            所有数据: {
                Fields: theService.申请字段.map((af) => {
                    af.ReadOnly = true;
                    af.Required = false;

                    return af;
                }),
                data: doc,
            },
        };
        
        return next();
    },
    router.CreateDocument('sapplication'),
);

module.exports = router;
